package com.xb.controller;

import com.xb.entity.Dept;
import com.xb.entity.User;
import com.xb.service.DeptService;
import com.xb.service.UserService;
import com.xb.utils.FileUploadUtils;
import com.xb.utils.PageEntity;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@WebServlet("/user/*")
public class UserController extends BaseController{

    private UserService userService=new UserService();

    private DeptService deptService=new DeptService();


    /**
     * 去微信扫码登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void wx_login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Properties properties = new Properties();

        properties.load(UserController.class.getClassLoader().getResourceAsStream("config.properties"));

        String appId = properties.getProperty("wx.AppID");
        String redirectUri = properties.getProperty("wx.redirect_uri");

        String url="https://open.weixin.qq.com/connect/qrconnect" +
                "?appid="+appId +
                "&redirect_uri="+redirectUri +
                "&response_type=code" +
                "&scope=snsapi_login" ;

        resp.sendRedirect(url);
    }

        /**
         * 添加/取消关注
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void addFocus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // Map<String, String> param = getParam(req);
        long focusId = Long.parseLong(req.getParameter("userId"));

        //查询当前用户是否关注过该用户
        Boolean flag= userService.isFocus(loginUser.getId(),focusId);
        if(flag){
            //已经关注过，是来取消关注的
            userService.delFocus(loginUser.getId(),focusId);
            writerObjToString(resp,"0");
        }else {
            //没有关注过，是来关注的
            userService.addFocus(loginUser.getId(),focusId);
            writerObjToString(resp,"1");
        }


    }

        /**
         * 我的关注列表+分页
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void findFocusPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String> param = getParam(req);
        Integer currPage=Integer.parseInt(param.get("currPage"));

         PageEntity<User> pageData= userService.findFocusPage(loginUser.getId(), currPage);

         req.setAttribute("pageData",pageData);

         req.getRequestDispatcher("/html/my_user.jsp").forward(req,resp);
    }

        /**
         * 用户头像上传
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void uploadPic(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String> param = getParam(req);
        //上传文件到upload路径，并且返回文件名称
        String fileName = FileUploadUtils.upload("/upload", req);

        //图片互联网地址
        String url="http://localhost:8080/upload/"+fileName;

        //更新session中用户的图像地址
        HttpSession session = req.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        loginUser.setPic(url);

        //更新数据库中图片地址
        userService.updataPic(loginUser.getId(),url);


        //将图片互联网地址写给前端
        writerObjToString(resp,url);
//        resp.getWriter().write(url);
    }


        /**
         * 用户数据修改
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");

        Map<String, String> param = getParam(req);

        HttpSession session = req.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        loginUser.setRealName(param.get("realName"));
        loginUser.setDeptId(Long.parseLong(param.get("deptId")));
        loginUser.setDeptName(param.get("deptName"));
        loginUser.setPhone(param.get("phone"));
        try {
            loginUser.setAge(Long.parseLong(param.get("age")));
        } catch (NumberFormatException e) {

        }
        loginUser.setInfo(param.get("info"));
        loginUser.setGender(param.get("gender"));

        String isSecret = param.get("isSecret");
        if("".equals(isSecret)){
            //说明前端没有勾选私密，代表公开，1
            loginUser.setIsSecret("1");
        }else {
            //说明前端有勾选私密，代表私密，0
            loginUser.setIsSecret("0");
        }

        userService.update(loginUser);
        //重新去更新资料
        resp.sendRedirect("/user/userDetail");
    }


        /**
         * 查询用户详细信息
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void userDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端所有的参数（不可能返回null）
        Map<String, String> param = getParam(req);


        String flag = param.get("flag");

        if("detail".equals(flag)){
            //代表查询别人的信息
            Long userId= Long.parseLong(param.get("userId"));
            //用户详情
            User user= userService.findById(userId);

            //粉丝数
            Integer fansCount=userService.findFansCount(userId);

            //被看数+1
            userService.updateLook(userId);

            req.setAttribute("user",user);
            req.setAttribute("fansCount",fansCount);
            req.getRequestDispatcher("/html/user_detail.jsp").forward(req,resp);

        }else {
            //代表查询自己的信息
            HttpSession session = req.getSession();
            User loginUser = (User) session.getAttribute("loginUser");

            //查询部门信息
            List<Dept> deptList = deptService.findAll();

            //关注数
            Integer focusCount=userService.findFocusCount(loginUser.getId());
            req.setAttribute("focusCount",focusCount);
            req.setAttribute("deptList",deptList);
            req.getRequestDispatcher("/html/user_look.jsp").forward(req,resp);
        }

    }


        /**
         * 根据部门Id去查询用户信息
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void findByDeptId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     Long deptId= Long.parseLong(req.getParameter("deptId"));
     List<User> userList= userService.findByDeptId(deptId);

     writerObjToString(resp,userList);

    }
        /**
         * 用户搜索加分页
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void findPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取前端所有的参数（不可能返回null）
        Map<String, String> param = getParam(req);
        //当前页
        Integer currPage = Integer.parseInt(param.get("currPage"));

        //搜索条件
        String realName = param.get("realName");

        //根据条件查询分页数据
        PageEntity<User> pageData= userService.findPage(currPage,realName);

        //当前登录的人的关注的列表
        List<Long> userFocusIdList= userService.findFocusIdList(loginUser.getId());


        req.setAttribute("pageData",pageData);
        req.setAttribute("realName",realName);
        req.setAttribute("userFocusIdList",userFocusIdList);
        req.getRequestDispatcher("/html/user.jsp").forward(req,resp);
    }


    /**
     * 搜索用户
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String searchVal = req.getParameter("realName");

        List<User> userList= userService.search(searchVal);
        req.setAttribute("userList",userList);
        req.setAttribute("searchVal",searchVal);

        req.getRequestDispatcher("/html/user.jsp").forward(req,resp);

    }

    /**
     * 查询用户列表
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        List<User> userList= userService.findAll();

        req.setAttribute("userList",userList);

        req.getRequestDispatcher("/html/user.jsp").forward(req,resp);


    }




        /**
         * 校验邮箱
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */

    protected void checkEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String email = req.getParameter("email");
        User user= userService.findByEmail(email);

        if(user==null){
            resp.getWriter().write("1");
        }
        resp.getWriter().write("0");
    }


    /**
     * 校验用户名
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    protected void checkUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        User user= userService.findByUsername(username);

        if(user==null){
            resp.getWriter().write("1");
        }
        resp.getWriter().write("0");
    }

    /**
     * 用户登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");

        HttpSession session = req.getSession();
        Object sessionCode = session.getAttribute("sessionCode");

        if(!checkCode.equalsIgnoreCase(sessionCode.toString())){
            session.setAttribute("error","验证码错误！");
            resp.sendRedirect("/index.jsp");
            return;
        }

        User user = userService.findByUsername(username);
        if(user==null || !user.getPassword().equals(password)){
            session.setAttribute("error","用户名或密码错误！");
            resp.sendRedirect("/index.jsp");
            return;
        }


        session.setAttribute("loginUser",user);
        session.removeAttribute("error");

        //签发cookie
        String rememberMe = req.getParameter("rememberMe");
        if("1".equals(rememberMe)){
            //前端勾选了记住我
            Cookie cookie = new Cookie("userId", user.getId() + "");
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*7);
            resp.addCookie(cookie);

        }


        resp.sendRedirect("/html/home.jsp");


    }

    /**
     * 用户注册
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */


    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");

        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setRegisterTime(new Date());
        user.setLook(0L);

        //用户注册
        userService.register(user);

        resp.sendRedirect("/index.jsp");
    }


    /**
     * 退出登录，销毁cookie
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void Logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie=new Cookie("userId","x");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        resp.addCookie(cookie);

        req.getSession().invalidate();
        resp.sendRedirect("/index.jsp");

    }


    }
